package com.gvitz.transaction.database;

import java.security.GeneralSecurityException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.widget.Toast;

import com.gvitz.transaction.R;
import com.gvitz.transaction.activities.BillActivity;
import com.gvitz.transaction.models.transaction;
import com.gvitz.transaction.utils.Config;
import com.gvitz.transaction.utils.EncriptUtils;

public class webserviceTransaction {
	
	
	 public ProgressDialog pDialog; 
	 public Context ctx;
	 public Activity act;
   	 private static final String NAMESPACE = "http://gvitz_webservice/";
   	 private static final String URL = Config.IP + "WStransactions?wsdl"; 
	 
	 
	public webserviceTransaction(Context ctx, Activity act) {
		super();
		this.ctx = ctx;
		this.act = act;
		Config.trustEveryone();
	}

   public void makeTransaccion(String monto, String descripcion, String usuario_id, String tarjeta_id, String vendedor_id,String pin){
	    
	    new makeTransaccionA().execute(monto, descripcion, usuario_id, tarjeta_id, vendedor_id, pin);
   }
   
   public void GetTransaccions(String usuario){
	    
	    new getTransaccionsA().execute(usuario);
  }

   public class makeTransaccionA extends AsyncTask< String, String, String > {
    	

   	 private static final String METHOD_NAME ="makeTransaction";
   	 private static final String SOAP_ACTION =  "http://gvitz_webservice/makeTransaction";
   	 String monto, descripcion,usuario_id, tarjeta_id, vendedor_id,pin, result;
   		 
        protected void onPreExecute() {
   		    
        	pDialog = new ProgressDialog(act);
            pDialog.setMessage("Realizando pago");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
            
        }
 
		@SuppressWarnings("deprecation")
		protected String doInBackground(String... params) {
			
              monto=params[0];
              descripcion=params[1];
              usuario_id=params[2];
              tarjeta_id=params[3];
              vendedor_id=params[4];
              pin=params[5];
			
			  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

			  // Crear variables
			  PropertyInfo propInfo=new PropertyInfo();
			  propInfo.name="encode";
			  propInfo.type=PropertyInfo.STRING_CLASS;

			  PropertyInfo propInfo1=new PropertyInfo();
			  propInfo1.name="descripcion";
			  propInfo1.type=PropertyInfo.STRING_CLASS;
			  
			  PropertyInfo propInfo2=new PropertyInfo();
			  propInfo2.name="usuario_id";
			  propInfo2.type=PropertyInfo.STRING_CLASS;
			  
			  PropertyInfo propInfo3=new PropertyInfo();
			  propInfo3.name="pin";
			  propInfo3.type=PropertyInfo.STRING_CLASS;
			  
			  
			  SharedPreferences prefs=  act.getSharedPreferences("preferencias", Context.MODE_PRIVATE);
			  String cadena = monto + "-" + tarjeta_id + "-" + vendedor_id;			  
			  String enc = "";
				try {
					enc = EncriptUtils.encrypt(cadena,prefs.getString("encode_usuario",""));
				} catch (GeneralSecurityException e1) {
					e1.printStackTrace();
				}

			  //agregar variables
			  request.addProperty(propInfo,enc); 
			  request.addProperty(propInfo1,descripcion);
			  request.addProperty(propInfo2,usuario_id);
			  request.addProperty(propInfo3,new String(Hex.encodeHex(DigestUtils.sha256(pin))));
			  

			  //realizar pedido
			  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
			  envelope.setOutputSoapObject(request);			  
			  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
					
				  try {
				   
					  //realizar peticion
					   androidHttpTransport.call(SOAP_ACTION, envelope);				  
					   SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();					   
					   result = resultsRequestSOAP.toString();
				   
				  } catch (Exception e) {
					  
					  result="Error de conexion";
					  e.printStackTrace();
					 
				  }
			return result;	
		}
       
        protected void onPostExecute(final String result) {
                    
				pDialog.dismiss();			
				
				if(result.subSequence(0,2).equals("ok")){
					
					// Fecha
					 Date currentLocalTime = new Date();
					 DateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm");   
			 		 String localTime = date.format(currentLocalTime); 
			 		 
			 		 //base da datos
			 		 gvitzDB  dbHelper = new gvitzDB(ctx);
			 		 String nombre = dbHelper.GetNombreVendedor(Integer.parseInt(vendedor_id));
			 		 String tarjeta = dbHelper.GetTarjeta(Integer.parseInt(tarjeta_id)).getCard_number();
			 		 dbHelper.AddTransaccion(new transaction(Integer.parseInt(result.substring(2)),Integer.parseInt(monto),Integer.parseInt(vendedor_id), nombre, localTime,Integer.parseInt(tarjeta_id)));	 		 		 		 
					
			 		 //avisar al cliente
					 Toast.makeText(ctx,"Transaccion exitosa", Toast.LENGTH_LONG).show();
					 
					 Intent intent = new Intent(act, BillActivity.class);
				 	 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
				        
				        // Pass data to the new activity
				        intent.putExtra("id",result.substring(2));
				        intent.putExtra("monto",monto);
				        intent.putExtra("tarjeta",tarjeta);
				        intent.putExtra("descripcion",descripcion);
				        intent.putExtra("comercio",nombre);
				        intent.putExtra("fecha",localTime);

				 	 act.startActivity(intent); 
				 	 act.overridePendingTransition (R.anim.open_next, R.anim.close_main);						
				}
				
				else{
		        	
		        	Vibrator vibrator =(Vibrator) act.getSystemService(Context.VIBRATOR_SERVICE);
		    	    vibrator.vibrate(200);	
		    	    Toast.makeText(ctx,result, Toast.LENGTH_LONG).show();
					
				}
          
          }		
        }
	
   public class getTransaccionsA extends AsyncTask< String, String, String > {
    	
	   	 private static final String METHOD_NAME ="sentT";
	   	 private static final String SOAP_ACTION =  "http://gvitz_webservice/sentT";
	   	 String usuario, result;
	   		 
	        protected void onPreExecute() {	   		    
	        //nada de momento
	        }
	 
			@SuppressWarnings("deprecation")
			protected String doInBackground(String... params) {
				
	              usuario =params[0];

				  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

				  PropertyInfo propInfo=new PropertyInfo();
				  propInfo.name="id_usuario";
				  propInfo.type=PropertyInfo.INTEGER_CLASS;
				  
				  request.addProperty(propInfo,Integer.parseInt(usuario)); 


				  //realizar pedido
				  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
				  envelope.setOutputSoapObject(request);			  
				  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
						
					  try {
					   
						  //realizar peticion
						   androidHttpTransport.call(SOAP_ACTION, envelope);				  
						   SoapObject  resultsRequestSOAP = (SoapObject) envelope.bodyIn;
						   int count = resultsRequestSOAP.getPropertyCount();
						   
						   gvitzDB dbHelper= new gvitzDB(ctx);
						   for (int i=0; i<count; i++){
  
							
							   SoapObject result =(SoapObject) resultsRequestSOAP.getProperty(i);
							   
							   Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(result.getProperty(1).toString());
							   DateFormat datef = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
							   
							   transaction trans = new transaction(Integer.parseInt(result.getProperty(2).toString()), 
									   							   Double.parseDouble(result.getProperty(4).toString()), 
									   							   Integer.parseInt(result.getProperty(6).toString()), 
									                               result.getProperty(3).toString(), 
									                               datef.format(date) , 
									                               Integer.parseInt( result.getProperty(5).toString()));
							   dbHelper.AddTransaccion(trans);
							   
							   }
						  
						   result = "ok";
					   
					  } catch (Exception e) {
						  result="SOAP";
						  e.printStackTrace();
					  }
				return result;	
			}
	       
	        protected void onPostExecute(String result) {                   							    
	        	// nada de momento	                    
	          }		
	        }
	
    

}
